package top.kangshuai.service.impl;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.kangshuai.dao.TbTokenDAO;
import top.kangshuai.dao.TbTokenInfoDAO;
import top.kangshuai.entity.TbToken;
import top.kangshuai.service.TokenService;
import top.kangshuai.utils.MyUtils;

/**
 * 
 * @author ks187
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TokenServiceImpl implements TokenService {
  @Autowired
  private TbTokenDAO tbTokenDAO;
  @Autowired
  private TbTokenInfoDAO tbTokenInfoDAO;

  private TbToken newToken() throws Exception {
    TbToken token = new TbToken();
    token.setToken(UUID.randomUUID().toString());
    tbTokenDAO.addToken(token);
    return token;
  }

  @Override
  public TbToken checkToken(TbToken token) throws Exception {
    // 没有传入就返回新的
    if (token == null || MyUtils.isEmpty(token.getToken())) {
      return newToken();
    }
    // 数据库效应
    TbToken sToken = tbTokenDAO.queryToken(token);
    // 校验不通过就返回新的
    if (sToken == null) {
      return newToken();
    }
    // 更新时间
    tbTokenDAO.updateToken(sToken);
    return sToken;
  }
@Override
  public int deleteTokens() throws Exception{
  //先删除tokeninfo 在删除token
  tbTokenInfoDAO.deleteTokenInfos();
  return tbTokenDAO.deleteTokens();
}
}
